<template>
  <div>
    <van-button
      v-if="!is_followed"
      :loading="follow_loading"
      class="follow-btn"
      type="info"
      color="#3296fa"
      round
      size="small"
      icon="plus"
      @click="guanzhuHandler"
      >关注</van-button
    >
    <van-button
      v-else
      :loading="follow_loading"
      class="follow-btn"
      round
      size="small"
      @click="guanzhuHandler"
      >已关注</van-button
    >
  </div>
</template>

<script>

import { addFollowingAjax,  deleteFollowingAjax } from '@/api/user'


export default {
  name: 'FollowingUser',
  // 父组件用的v-model 绑定的关注按钮 所以用这种模式
  model: {
    prop: 'is_followed',
    event: 'FOLLOWING_EVENT'
  },

  props: {
    is_followed: {
      type: Boolean,
      required: true
    },
    userId: {
      type: [Number, String],
      required: true
    }
  },
  data() {
    return {
      follow_loading: false
    }
  },
  created() {},
  methods: {
    async guanzhuHandler() {
      this.follow_loading = true
      try {
        // 要判断用户㐊  已关注， 还是未关注
        if (this.is_followed) {
          // 这个逻辑表示 已经关注过了；  取消关注
          await deleteFollowingAjax(this.userId)
          this.$toast.success('取消关注成功')
        } else {
          // 这个里面表示没有关注，  新增关注
          await addFollowingAjax(this.userId)
          this.$toast.success('关注成功，感谢有你')
        }
        // this.is_followed = !this.is_followed 直接修改父组件传递进来的值是错误写法，vue单向数据流
        this.$emit('FOLLOWING_EVENT', !this.is_followed)
      } catch (err) {
        console.log(err.response.status)
        if (err.response && err.response.status == 400) {
          this.$toast.fail('自己不能关注自己')
        } else {
          this.$toast.fail('用户关注失败')
        }
      }
      this.follow_loading = false
    }
  }
}
</script>

<style lang="less" scoped></style>
